//
//  JGCityViewController.m
//  JGMeiTuanHD
//
//  Created by JJetGu on 15/9/10.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGCityViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "MJExtension.h"
#import "JGCityGroup.h"
#import "JGConst.h"
#import "UIView+AutoLayout.h"
#import "JGCitySearchResultViewController.h"
#import "JGCityTableViewCell.h"

#import <CoreLocation/CLLocationManagerDelegate.h>
#import "AFNetworking.h"
#import "JGSelectedCityTool.h"

/** 城市定位失败提示 */
#define LocationFaileString @"定位失败，请点击加载"
/** 城市定位中提示 */
#define LocationingString @"定位中..."

#define BAIDU_GEO_API @"http://api.map.baidu.com/geocoder"

@interface JGCityViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, JGCityTableViewCellDelegate, CLLocationManagerDelegate>
{
    NSMutableArray *_newCityGroups;
    NSMutableArray *_newTitleArray;
    NSArray *_locationCity;
}
@property (nonatomic, strong) NSArray *cityGroups;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIButton *cover;
- (IBAction)coverClick:(UIButton *)sender;
@property (nonatomic, weak)JGCitySearchResultViewController *citySearchResultVC;
/** 定位 */
@property (nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation JGCityViewController

-(JGCitySearchResultViewController *)citySearchResultVC
{
    if (!_citySearchResultVC) {
        JGCitySearchResultViewController *citySearchResultVC = [[JGCitySearchResultViewController alloc] init];
        [self addChildViewController:citySearchResultVC];
        self.citySearchResultVC = citySearchResultVC;
        
        [self.view addSubview:self.citySearchResultVC.view];
        
        [self.citySearchResultVC.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
        [self.citySearchResultVC.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.searchBar withOffset:15];
    }
    
    return _citySearchResultVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 基本设置
    self.title = @"切换城市";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(close) image:@"btn_navigation_close" highImage:@"btn_navigation_close_hl"];
    //    self.tableView.sectionIndexBackgroundColor = [UIColor redColor];
    self.tableView.sectionIndexColor = [UIColor blackColor];
    
    // 加载城市数据
    self.cityGroups = [JGCityGroup objectArrayWithFilename:@"cityGroups.plist"];
    //加载新城市数据
    NSMutableArray *tempCityGroups = [NSMutableArray array];
    _newCityGroups = [NSMutableArray arrayWithObjects:@"定位城市",@"最近访问城市", nil];
    for (JGCityGroup *group in self.cityGroups) {
        [tempCityGroups addObject:group];
    }
    [_newCityGroups addObjectsFromArray:tempCityGroups];
    
    //tableView的索引
    _newTitleArray = [NSMutableArray arrayWithObjects:@"#",@"$", nil];
    [_newTitleArray addObjectsFromArray:[self.cityGroups valueForKeyPath:@"title"]];
    
    //创建定位
    self.locationManager =[[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startUpdatingLocation];
    
    //定位数组初始化
    _locationCity = [NSArray arrayWithObject:LocationingString];
    
    self.searchBar.tintColor = JGColor(32, 191, 179);
}

- (void)close
{
    if ([JGSelectedCityTool selectedCityMessage] == nil) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择城市" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - 搜索框代理方法
/**
 *  键盘弹出:搜索框开始编辑文字
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    // 1.隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    // 3.修改搜索框的背景图片
    [searchBar setBackgroundImage:[UIImage imageNamed:@"bg_login_textfield_hl"]];
    
    // 3.显示搜索框右边的取消按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    
    // 4.显示遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.5;
    }];
}

/**
 *  键盘退下:搜索框结束编辑文字
 */
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    // 1.显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:YES];

    // 3.修改搜索框的背景图片
    [searchBar setBackgroundImage:[UIImage imageNamed:@"bg_login_textfield"]];
    
    // 3.隐藏搜索框右边的取消按钮
    [searchBar setShowsCancelButton:NO animated:YES];
    
    // 4.隐藏遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.0;
    }];
    
    // 5.移除搜索结果
    self.citySearchResultVC.view.hidden = YES;
    searchBar.text = nil;
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length) {
        self.citySearchResultVC.view.hidden = NO;
        self.citySearchResultVC.searchText = searchText;
    } else {
        self.citySearchResultVC.view.hidden = YES;
    }
}


- (IBAction)coverClick:(UIButton *)sender {
    [self.searchBar resignFirstResponder];
}


#pragma mark - tableView数据源方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _newCityGroups.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section ==1 || section ==2) {
        return 1;
    }
    JGCityGroup *group = _newCityGroups[section];
    return group.cities.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section ==2) {
        
        static NSString *myCityID = @"JGCity";
        JGCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCityID];
        if (cell == nil) {
            cell = [[JGCityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myCityID];
            cell.delegate = self;
        }
        if (indexPath.section == 0) {
            //定位城市
            cell.cityNames = _locationCity;
            
        } else if (indexPath.section == 1) {
            //最近访问城市
            cell.cityNames = [self cityNamesFromeUserDefault];
        } else {
            JGCityGroup *group = _newCityGroups[indexPath.section];
            cell.cityNames = group.cities;
        }
        return cell;
    } else {
        static NSString *ID = @"city";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        }
        
        JGCityGroup *group = _newCityGroups[indexPath.section];
        cell.textLabel.text = group.cities[indexPath.row];
        
        return cell;
    }
}

#pragma mark - tableView代理方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0 || section ==1) {
        return _newCityGroups[section];
    }
    JGCityGroup *group = _newCityGroups[section];
    return group.title;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //    NSMutableArray *titles = [NSMutableArray array];
    //    for (MTCityGroup *group in self.cityGroups) {
    //        [titles addObject:group.title];
    //    }
    //    return titles;
    return _newTitleArray;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return 54;
    } else if(indexPath.section == 2){
        return 210;
    } else {
        return 44;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     if (!(indexPath.section == 0 || indexPath.section == 1 || indexPath.section ==2))
     {
         JGCityGroup *group = self.cityGroups[indexPath.section];
         NSString *cityName = group.cities[indexPath.row];
         // 发出通知
         [self postNotificationWithCity:cityName];
     }
}

#pragma mark - 发出选中城市名字通知
-(void)postNotificationWithCity:(NSString *)cityName
{
    [JGNotificationCenter postNotificationName:JGCityDidChangeNotification object:nil userInfo:@{JGSelectCityName : cityName}];
    //保存最近选中城市
    [self saveCityNameToUserDefault:cityName];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - HMCityTableViewCellDelegate
-(void)cityTableViewCell:(JGCityTableViewCell *)cityTableViewCell didClickLocationBtnTitle:(NSString *)title
{
    NSLog(@"定位城市：%@",title);
    if ([title isEqualToString:LocationFaileString] || [title isEqualToString:LocationingString] || title == nil || [title isEqualToString:@""]) {
        self.locationManager.delegate = self;
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
        //刷新tableView
        _locationCity = @[LocationingString];
        [_tableView reloadData];
    } else {
        // 发出通知
        [self postNotificationWithCity:title];
    }
}

-(void)cityTableViewCell:(JGCityTableViewCell *)cityTableViewCell didClickBtnTitle:(NSString *)title
{
    // 发出通知
    [self postNotificationWithCity:title];
}

#pragma mark ---CLLocationManagerDelegate---
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //刷新tableView
    _locationCity = [NSArray arrayWithObject:LocationFaileString];
    [_tableView reloadData];
    self.locationManager.delegate = nil;
    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = manager.location;
    
    // 1.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"output"] = @"json";
    params[@"location"] = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
    
    // 1.创建请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    // 2.发送请求
    [mgr GET:BAIDU_GEO_API parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        if (dic) {
            if ([dic[@"status"] isEqualToString:@"OK"]) {
                NSString *cityName = dic[@"result"][@"addressComponent"][@"city"];
                //刷新tableView
                if ([cityName containsString:@"市"]) {
                    cityName = [cityName substringToIndex:cityName.length-1];
                }
                _locationCity = @[cityName];
                [_tableView reloadData];
                
                [self.locationManager stopUpdatingLocation];
                return;
            }
        }
        //刷新tableView
        _locationCity = [NSArray arrayWithObject:LocationFaileString];
        [_tableView reloadData];
        [self.locationManager stopUpdatingLocation];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.locationManager stopUpdatingLocation];
        //刷新tableView
        _locationCity = [NSArray arrayWithObject:LocationFaileString];
        [_tableView reloadData];
    }];
}

#pragma mark - 保存最近访问城市的名字
-(void)saveCityNameToUserDefault:(NSString *)cityName
{
    NSMutableArray *cityNames = [self cityNamesFromeUserDefault];
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempArray addObject:cityName];
    [tempArray addObjectsFromArray:cityNames];
    cityNames = tempArray;
    for (int i = 1; i<cityNames.count; i++) {
        if ([cityNames[i] isEqualToString:cityName]) {
            [cityNames removeObject:cityNames[i]];
            [cityNames insertObject:cityName atIndex:0];
        }
    }
    if (cityNames.count > 3) {
        [cityNames removeLastObject];
    }
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:cityNames forKey:JGRecentSelectedCityName];
    [user synchronize];
}

-(NSMutableArray *)cityNamesFromeUserDefault
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray *cityNames = [user objectForKey:JGRecentSelectedCityName];
    if (cityNames ==nil) {
        cityNames = [NSMutableArray array];
    }
    return cityNames;
}
@end
